package org.filecollector.msgcontroller.answers.converters;

import com.google.gson.*;
import org.filecollector.msgcontroller.answers.AnswerMessage;
import org.filecollector.msgcontroller.answers.SyncAnswerMessage;

import java.lang.reflect.Type;

public class SyncAnswerConverter implements JsonSerializer<SyncAnswerMessage>, JsonDeserializer<SyncAnswerMessage>{

    @Override
    public SyncAnswerMessage deserialize(
            JsonElement jsonElement,
            Type type,
            JsonDeserializationContext jsonDeserializationContext
    ) throws JsonParseException {
        JsonObject object = jsonElement.getAsJsonObject();
        return new SyncAnswerMessage(
                object.get("operation_id").getAsLong(),
                AnswerMessage.deserialize(object.get("message").toString())
        );
    }

    @Override
    public JsonElement serialize(
            SyncAnswerMessage message,
            Type type,
            JsonSerializationContext jsonSerializationContext
    ) {
        JsonObject object = new JsonObject();
        object.addProperty("operation_id", message.operationID());
        object.add("message", message.answerMessage().getAsElement());
        return object;
    }
}
